<?php


namespace app\api\model;


use ApiOper;
use app\common\library\IDMan;
use app\common\model\BaseModel;
use common;
use think\Db;
use think\db\Query;

class ExchangeModel extends BaseModel
{
    protected $name = 'item_excharge';
    protected $pk = 'id';

    //type 1:会员卡 2:骑行卡 3:优惠卷 4实物
//    var $ex_changecards = [
//        [
//            'id' => 1,
//            'type' => 1,
//            'name' => '30天会员卡',
//            'score' => 990, //690
//            'duration' => 24 * 30 * 3600,
//        ],
//        [
//            'id' => 2,
//            'type' => 2,
//            'name' => '5次·7日骑行卡',    //名字
//            'score' => 1000,
//            'duration' => 7*24*3600,   //骑行卡有效时间
//            'free_count' => 5,              //次数
//        ],
//        [
//            'id' => 3,
//            'type' => 3,
//            'name' => '优惠卷',
//            'score' => 9980, //2990
//            'amount' => 100,
//            'duration' =>  7*24*3600,   //骑行卡有效时间
//        ],
//    ];

    function card_list($city_id,$pos,$limit,$cd)
    {
        $selectlist = [
            'id' => 'string',               //商品id
            'city_id' => 'string',          //城市id
            'type' => 'int',                //类型 type 1:会员卡 2:骑行卡 3:优惠卷 4实物
            'name' => 'string',             //商品名
            'amount' => 'int',              //兑换积分
            'img' => 'string',              //图片
            'duration'=> 'int',             //时长 秒为单位
            'discount' => 'int',            //每次兑换多少张，只有骑行卡有几次，其他默认一张
            'dismoney' => 'int',            //优惠卷抵扣多少钱
            'free_count' => 'int',           //商场剩余数量
            'count' => 'int',                //总数量
            'create_time' => 'string',       //时间
            'update_time' => 'string',       //更新时间
            'begin_time'  => 'string',        //兑换开始时间
            'end_time'    => 'string',        //结束兑换时间
        ];

        $beans = [
            'is_delete' => 0,
        ];


        if (!empty($city_id)) {
            $beans['city_id'] = [['=',null],['=',$city_id],'or'];
        }

        $query = new Query();

        if (isset($cd['user'])){
            if ($cd['user'] == 1){
                $now =date('Y-m-d H:i:s');
                $beans[] = $now;
                $beans[] = $now;
                $query->where('begin_time','<=',$now)
                    ->whereOr('end_time','>',$now);
            }
        }


        $rows = $this->where($beans)->where($query)->field(array_keys($selectlist))->order('create_time','asc')->limit($pos,$limit)->select();

        if (empty($rows)){
            return [];
        }
        else{
            return $rows->toArray();
        }
    }

    function query_card_info($id,$city_id)
    {
        $selectlist = [
            'id' => 'string',
            'city_id' => 'string',
            'type' => 'string',
            'name' => 'string',
            'amount' => 'int',
            'img' => 'string',
            'duration'=> 'int',
            'discount' => 'int',
            'dismoney' => 'int',            //优惠卷抵扣多少钱
            'free_count' => 'int',
            'count' => 'int',
            'create_time' => 'string',
            'update_time' => 'string',
        ];


        $row = $this->where('id',$id)->field(array_keys($selectlist))->find();

        if (empty($row))
        {
            return null;
        }

        return $row->toArray();
    }

    function submit($city_id, $userinfo, $card_id)
    {
        $card_info = $this->query_card_info($card_id,$city_id);
        if (empty($card_info)) {
            $this->throw_myexception(X_ERROR, "没有该兑换商品!");
        }

        if ($card_info['count'] >0 && $card_info['free_count'] <=0) {
            $this->throw_myexception(X_ERROR, "该商品已经兑换完成!");
        }

        if ($userinfo['score'] < $card_info['amount']){
            $this->throw_myexception(X_ERROR, "积分不足，无法兑换!");
        }

        (new UserModel())->incr_score($userinfo['id'],-$card_info['amount']);

        //$order_id = IDMan::order_id();
        switch ($card_info['type'])
        {
            case 1:
                {
                    //会员卡
                    $membership_expire_time = (new UserMembershipOrderModel())->add_day_membership($userinfo,$card_info['name'],$card_info['duration'],PAY_GATEWAY_SCORE);
                    (new UserModel())->set_membership_expire_time($userinfo['id'], $membership_expire_time);
                }
                break;
            case 2:
                {
                    //骑行卡
                    (new UserRideCardOrderModel())->add_ridecard($city_id,$userinfo,PAY_GATEWAY_SCORE,$card_info['name'],$card_info['duration'],$card_info['discount']);
                }
                break;
            case 3:
                {
                    //优惠卷
                    for($i = 0 ; $i < $card_info['discount'];++$i){
                        (new CouponModel())->coupon_for_type_1($userinfo['id'],$card_info['dismoney'],$card_info['duration'],'积分兑换');
                    }

                }
                break;
        }

        $this->item_dec($card_info);
        $this->record($city_id,$userinfo,SCORE_GATEWAY_EXCHANGE,-$card_info['amount'],$card_info['id'],$card_info['name'],$card_info['img']);

    }

    function record($city_id,$userinfo,$order_type,$score,$item_id = null,$item_name=null,$item_img =null)
    {
        $order_id =  IDMan::city_order_id($city_id);

        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_type' => $order_type,
            'order_state' => 100,
            'score' => $score,
        ];

        if (isset($item_id)){
            $order_info['item_id'] = $item_id;
        }

        if (isset($item_name)){
            $order_info['item_name'] = $item_name;
        }

        if (isset($item_img)){
            $order_info['item_img'] = $item_img;
        }

        Db::table('tb_user_excharge_order')->insert($order_info);
    }


    function item_dec($item)
    {

        if ($item['free_count'] >0 && $item['count']>0)
        {
            Db::table('tb_item_excharge')
                ->where('id', $item['id'])
                ->dec('free_count',1);
        }
    }

    function record_list($user_id,$pos, $limit,$cd)
    {
        $selectlist = [
            'id' => 'string',                   //id
            'city_id' => 'string',              //城市id
            'user_id' => 'string',              //玩家id
            'user_name' => 'string',            //玩家名
            'score' => 'int',                   //兑换积分
            'item_id' => 'string',               //商品id
            'item_name' => 'string',             //商品名
            'item_img' => 'string',              //商品图片
            'order_type'=> 'string',             //积分产生的形式
            'create_time' => 'string',           //创建时间
            'order_state' => 'int',             //100已兑换 1:开始兑换
        ];

        $beans = [
            'order_state' => 100
        ];
        if (!empty($user_id)) {
            $beans['user_id'] = $user_id;
        }

        if (!empty($cd['order_type'])){
            $beans['order_type'] = $cd['order_type'];
        }


        $rows = $this->where($beans)->field(array_keys($selectlist))->order('create_time','desc')->limit($pos,$limit)->select();

        if (empty($rows)){
            return [];
        }
        else{
            return $rows->toArray();
        }
    }

    function add_item($item){
        $order_id =  IDMan::order_id();

        ApiOper::instance()->append_creater_info($item);

        $item['id'] =  $order_id;

        self::create($item,true);
    }

    function update_item($item,$item_id){

        ApiOper::instance()->append_updater_info($item);

        $where=[
            'id' => $item_id
        ];

        self::update($item,$where);
    }

    function del_item($item_id){
        $info =[
            'is_delete' => 1
        ];
        ApiOper::instance()->append_updater_info($info);

        $where=[
            'id' => $item_id
        ];

        self::update($info,$where);
    }

}